/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License. You may obtain a copy of the License at
	http://www.mozilla.org/MPL/
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import org.aswing.JPanel;
import org.aswing.SoftBoxLayout;

import com.bourre.data.collections.Map;
import com.bourre.data.iterator.Iterator;

import fever.exception.RuntimeException;
import fever.Fever;
import fever.log.FeverDebug;
import fever.utils.Stringifier;
import fever.utils.StringUtil;

import fvaswing.components.forms.FvFormField;

/**
 * Builds data forms.
 * 
 * <p>Take a look at <strong>fvaswing.components.forms</strong> package to see 
 * built-in form field alvailable in <strong>Fever</strong>. 
 * 
 * <p>All fields must be added before appending form onto other component.<br />
 * Otherwise, {@link #addField()} method throws a {@link fever.exception.RuntimeException} 
 * exceptions.
 * 
 * <p>In case that a field <strong>is not valid</strong>, tooltip text is available in label object to 
 * notice user where is his error.<br />
 * Same technic for <strong>required</strong> field.
 * 
 * <p>Form's data can be saved onto client's computer using the Fever application dedicated 
 * sharedobject. ( see {@link #save()} method.
 * 
 * <p>Example
 * {@code
 *   var container : Container = new JPanel( new BorderLayout( 5,5 ) );
 *   var nameField : FvStringField = new FvStringField( "Name", 1 );
 *   var surnameField : FvStringField = new FvStringField( "Surname", 1, 4 );
 *   var messageField : FvStringAreaField = new FvStringAreaField( "Message" );
 *   var emailField : FvEmailField = new FvEmailField( "Email" );
 *   var agreeField : FvCheckboxField = new FvCheckboxField( "I agree", true );
 *   
 *   var pollBox : FvCheckPollField = new FvCheckPollField( "Your hobbies" );
 *   pollBox.addChoice( "basket-ball" );
 *   pollBox.addChoice( "actionscript" );
 *   
 *   var passField : FvPasswordField = new FvPasswordField( "Password", 6, 10 );
 *   
 *   var pollRadio : FvRadioPollField = new FvRadioPollField( "Your opinion", true );
 *   pollRadio.addChoice( "bad" );
 *   pollRadio.addChoice( "execellent" );
 *   
 *   var form : FvForm = new FvForm( "myForm" );
 *   form.addField( nameField );
 *   form.addField( surnameField );
 *   form.addField( messageField );
 *   
 *   container.append( form, BorderLayout.CENTER );
 * }
 * 
 * <p>You can customize render validation state using {@link #setRenderStateHandler()} method.<br />
 * 2 ways to the job : 
 * <ul>
 *   <li>Setting a rendering method just for one field.</li>
 *   <li>Setting rendering method for all fields in form.</li>
 * <ul>
 * 
 * <p>Example : setting rendering method for one field : 
 * {@code
 *   var passField : FvPasswordField = new FvPasswordField( "Password", 6, 10 );
 *   passField.setRenderStateHandler( this, _renderValidationState ); 
 * } 
 *
 * <p>Example : setting rendering method for entire form : 
 * {@code
 *   var form : FvForm = new FvForm();
 *   form.setRenderStateHandler( this, _renderValidationState );
 * }
 * 
 * <p>Sample rendering method : 
 * {@code
 *   private function _renderValidationState( captionLabel : JLabel, caption : String, preventLabel : JLabel, must : Boolean, valid : Boolean, msg : String ) : Void
 *   {
 *   	if( valid )
 *   	{
 *   		captionLabel.setForeground( UIManager.getColor( 'TextField.foreground' ) );
 *   		
 *   		if( must )
 *   		{
 *   			preventLabel.setText( FvForm.REQUIRED_FIELD_SUFFIX );
 *   			preventLabel.setToolTipText( msg );
 *   		}
 *   		else
 *   		{
 *   			preventLabel.setText();
 *   			preventLabel.setToolTipText();
 *   		}
 *   	}
 *   	else
 *   	{
 *   		captionLabel.setForeground( ASColor.RED );
 *   		preventLabel.setText( FvForm.ERROR_FIELD_SUFFIX );
 *   		preventLabel.setToolTipText( msg );	
 *   	}
 *   }
 * }
 * 
 * @author Romain Ecarnot
 */
class fvaswing.components.FvForm extends JPanel
{
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private var _formName : String;
	private var _fieldMap : Map;
	private var _locked : Boolean;
	private var _oRenderScope;
	private var _fRenderMethod : Function;
	private var _pendingCall : Boolean;
	
	
	//-------------------------------------------------------------------------
	// Public Properties
	//-------------------------------------------------------------------------
	
	/** 
	 * Constant. <br />
	 * Defines suffix sub string for required field type.<br />
	 * Added to field caption.<br />
	 * Default is '(*)'
	 */
	public static var REQUIRED_FIELD_SUFFIX : String = '*';
	
	/** 
	 * Constant. <br />
	 * Defines suffix sub string for validation error in field.<br />
	 * Added to field caption.<br />
	 * Default is '(?)'
	 */
	public static var ERROR_FIELD_SUFFIX : String = '?';
	
	/**
	 * Property name identifier for sharedObject saving.<br />
	 * All forms are saved under this object name.
	 */
	public static function get CONFIG_ID() : String { return "forms"; }
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 * 
	 * @param formName A simple string to allow load / save actions on form.<br />
	 * If {@code formName} is undefined, form can't be loaded / saved from client 
	 * sharedobject.
	 */
	public function FvForm( formName : String )
	{
		super( new SoftBoxLayout( SoftBoxLayout.Y_AXIS, 5 ) );
		
		if( formName ) _formName = formName;
		else FeverDebug.WARN( 'Your form will not be savable cause of an undefined name.' );
		
		_init();
	}
	
	/**
	 * Delegates field state rendering to passed-in {@code renderingMethod} function.
	 * 
	 * @param scopeMethod Context where function is call.
	 * @param renderingMethod Function implementation to render field state
	 */
	public function setRenderStateHandler( scopeMethod, renderingMethod : Function ) : Void
	{
		if( scopeMethod && renderingMethod )
		{
			_oRenderScope = scopeMethod;
			_fRenderMethod = renderingMethod;	
		}
	}
	
	/**
	 * Adds passed-in {@link fvaswing.components.forms.FvFormField} into form.
	 * 
	 * <p>Add all your fields before append form onto other component.
	 * 
	 * @param field {@link fvaswing.components.forms.FvFormField} to add
	 * @param registrationID ( optional ) Allow load / save process using {@code registrationID} 
	 * data name.<br />
	 * If not defined, use the field label property, but if you use <strong>Localisation API</strong>, 
	 * field's label can change, so you must specify a explicit {@code registrationID } 
	 * 
	 * @throws {@link fever.exception.RuntimeException} if {@link #addField()} is called whereas 
	 * form is already in form ( appended ).
	 */
	public function addField( field : FvFormField, registrationID : String ) : String
	{
		if( !_locked )
		{
			if( !registrationID ) registrationID = _getFieldIdentifier( field.getCaption() );
			
			if( !_fieldMap.containsKey( registrationID ) )
			{
				_fieldMap.put( registrationID, field );
				append( field.getContainer() );
			}
			else FeverDebug.ERROR( 'A field is already registred with ' + registrationID + ' ID.');
			
			return registrationID;
		}
		else throw new RuntimeException( '.addField() is not authorized when form is already appended into component' ); 
	}
	
	/**
	 * Returns {@link fvaswing.components.forms.FvFormField} registred into form 
	 * with passed-in {@code registrationID}.
	 * 
	 * @param registrationID Field identifier ( defined using {@link #addField() } 
	 * method.
	 */
	public function getField( registrationID : String ) : FvFormField
	{
		if( !registrationID ) return null;
		
		return _fieldMap.get( registrationID );	
	}
	
	/**
	 * Returns {@code true} if form contains no field.
	 */
	public function isEmpty() : Boolean
	{
		return _fieldMap.isEmpty();	
	}
	
	/**
	 * Clears all fields value.
	 */
	public function clear() : Void
	{
		if( !isEmpty() )
		{
			var it : Iterator = _fieldMap.getValuesIterator();
			
			while( it.hasNext() )
			{
				var field : FvFormField = it.next();
				field.clear();
				field.showValidState();
			}
		}
	}
	
	/**
	 * Returns {@code true} if all form fields are valid.
	 * 
	 * <p>Depends of field properties.
	 */
	public function isFormDataValid() : Boolean
	{
		if( isEmpty() ) return true;
		
		var it : Iterator = _fieldMap.getValuesIterator();
		var b : Boolean = true;
		
		while( it.hasNext() )
		{
			var field : FvFormField = it.next();
			var result : Boolean = field.isFieldValid();
			b = ( b && result );
		}
		return b;
	}
	
	/**
	 * Loads form's data from local SharedObject.
	 * 
	 * <p>Forms's data must be saved using {@link #save()} method in order to 
	 * be loaded.
	 * 
	 * <p>Retreives SharedObject info using {@link #CONFIG_ID} name identifer 
	 * and the form's name ( defined in contructor argument ).
	 */
	public function load() : Void
	{
		var formsList : Object = Fever.application.config.load( CONFIG_ID );
		
		if( !formsList ) return;
		if( !formsList[ _formName ] ) return;
		
		var it : Iterator = _fieldMap.getKeysIterator();
		var o : Object = formsList[ _formName ];
		
		while( it.hasNext() )
		{
			var id : String = it.next();
			var field : FvFormField = _fieldMap.get( id );
			field.setValue( o[ id ] );
		}
	}
	
	/**
	 * Saves forms data into client's sharedobject.
	 * 
	 * <p>Form must have a valid name, defined by the form constructor.
	 * 
	 * <p>All forms are saved under {@link #CONFIG_ID} object in application 
	 * sharedobject.
	 */
	public function save() : Void
	{
		if( !_formName )
		{
			FeverDebug.ERROR( 'form is not saved cause of an undefined form name.' );
		}
		else if( _pendingCall )
		{
			FeverDebug.ERROR( 'form is not yet created. save action is disabled.' );
		}
		else
		{
			var formsList : Object = Fever.application.config.load( CONFIG_ID );
			
			if( !formsList ) formsList = new Object();
			
			var it : Iterator = _fieldMap.getKeysIterator();
			var o : Object = new Object();
			
			while( it.hasNext() )
			{
				var id : String = it.next();
				o[ id ] = FvFormField( _fieldMap.get( id ) ).getValue();
			}
			
			formsList[ _formName ] = o;
			Fever.application.config.save( CONFIG_ID, formsList );
		}
	}
	
	/**
	 * Returns string representation.
	 */
	public function toString() : String
	{
		return Stringifier.parse( this );
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	private function _init() : Void
	{
		_fieldMap = new Map();	
		_locked = false;
		_pendingCall = true;
		
		addEventListener( JPanel.ON_CREATED, _updateLabelWidth, this );
	}
	
	private function _getFieldIdentifier( source : String ) : String
	{
		var id : String = StringUtil.trim( source );
		id = StringUtil.replace( id, ' ', '_' );
		
		return id;
	}
	
	private function _updateLabelWidth() : Void
	{
		_pendingCall = false;
		
		if( isEmpty() ) return;
		
		var it : Iterator = _fieldMap.getValuesIterator();
		var field : FvFormField;
		var max : Number = 0;
		var lw : Number;
		
		while( it.hasNext() )
		{
			field = it.next();
			lw = field.getLabelWidth();
			max = ( lw > max ) ? lw : max;
		}
		
		it = _fieldMap.getValuesIterator();
		while( it.hasNext() )
		{
			field = it.next();
			field.init( max, _oRenderScope, _fRenderMethod );
			field.getContainer().revalidateIfNecessary();
		}
		
		_locked = true;
		
		load();
	}
}